package agent.dynamic;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.util.List;

public class MemoryCommand {

    //打印所有的内存信息
    public static void printMemory() {
        //获取内存信息，返回List的结果，List中有伊甸园区、老年代、元空间等对象
        //下面分堆和非堆，分开打印
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        System.out.println("堆内存：");
        //堆内存
        getMemoryInfo(memoryPoolMXBeans, MemoryType.HEAP);
        System.out.println("非堆内存：");
        //非堆内存
        getMemoryInfo(memoryPoolMXBeans,MemoryType.NON_HEAP);
    }

    /**
     * 处理内存信息
     * @param memoryPoolMXBeans 内存信息
     * @param heapType 堆或非堆
     */
    public static void getMemoryInfo(List<MemoryPoolMXBean> memoryPoolMXBeans,MemoryType heapType){
        memoryPoolMXBeans.stream().filter(x -> x.getType().equals(heapType))
                .forEach(x -> {
                    StringBuilder sb = new StringBuilder();
                    sb.append("name:")
                            .append(x.getName())
                            //使用量used
                            .append(" used:")
                            .append(x.getUsage().getUsed() / 1024 / 1024)  //byte转M
                            .append("M")
                            //申请量total
                            .append(" committed:")
                            .append(x.getUsage().getCommitted() / 1024 / 1024)
                            .append("M")
                            //最大值max
                            .append(" max:")
                            .append(x.getUsage().getMax() / 1024 / 1024)
                            .append("M");
                    System.out.println(sb);
                });

    }
}
